package com.dome.exception;

import com.dome.common.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;

/**
 * @param
 * @author tangshunkai
 */
@Slf4j
@ResponseBody
@ControllerAdvice(basePackages = "com.dome.controller")
public class CommonExceptionHandler {

    /**
     * 参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JsonResult handleVaildException(MethodArgumentNotValidException e){
        log.error(e.getMessage(), e);
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errorMap = new HashMap<>(1);
        bindingResult.getFieldErrors().forEach((fieldError)->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return JsonResult.failCodeMessageDate("400","参数校验异常",errorMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public JsonResult handleException(Throwable e){
        log.error(e.getMessage(), e);
        return JsonResult.failCodeMessage("500",e.getMessage());
    }

    /**
     * 全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public JsonResult handleException(Exception e){
        log.error(e.getMessage(), e);
        return JsonResult.failCodeMessage("500",e.getMessage());
    }

    /**
     * 数据库异常
     * @param e
     * @return
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public JsonResult handleDuplicateKeyException(DuplicateKeyException e){
        log.error(e.getMessage(), e);
        return JsonResult.fail("数据库中已存在该记录");
    }

    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(CommonException.class)
    public JsonResult handleCommonException(CommonException e){
        log.error(e.getMessage(), e);
        JsonResult r = new JsonResult();
        r.setCode(e.getCode());
        r.setMsg(e.getMessage());
        return r;
    }
}
